package org.jeecg.modules.filemanage.base.service.impl;

import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.log.Log;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jeecg.common.filemanage.api.IFileManageAPI;
import org.jeecg.modules.filemanage.base.service.IFileBaseApiService;
import org.jeecg.modules.filemanage.base.vo.FileContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;


@Service
public class FileBaseAPIImpl implements IFileManageAPI {
    @Autowired
    private FileTransManageServiceImpl fileTransManageService;

    @Async
    public void readFileStream(MultipartFile mf, String fileId){
        String suffix = "" ; //后缀名
        if(mf.getOriginalFilename().contains("."))
             suffix = mf.getOriginalFilename().split("\\.")[1];

        if(suffix.equalsIgnoreCase("doc")||suffix.equalsIgnoreCase("docx")||suffix.equalsIgnoreCase("txt")){
        try {
            InputStream is = mf.getInputStream();
            String content = null;
            //判断版本
            if(mf.getOriginalFilename().endsWith(".doc")||mf.getOriginalFilename().endsWith(".DOC"))
            {
                WordExtractor wordExtractor = new WordExtractor(is);
                content = wordExtractor.getText();
            }else if(mf.getOriginalFilename().endsWith(".docx")||mf.getOriginalFilename().endsWith(".DOCX")){
                XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(new XWPFDocument(is));
                content= xwpfWordExtractor.getText();
            }else{//txt
                content = new String(mf.getBytes(),"UTF-8");
            }
            FileContent fc = new FileContent();
            fc.setFileid(fileId);
            fc.setContent(content);
            fileTransManageService.saveOrUpdateEs(fileId, JSONObject.parseObject(JSONObject.toJSONString(fc)),"filemanage","filemanage_index");
        } catch (IOException e) {
            e.printStackTrace();
            Log.error("读取文件流内容失败");
        }
    }
    }
}
